from flask import Flask, render_template, request,jsonify,escape
import direction_of_walking
import json
import pandas as pd

app = Flask(__name__)

def log_request(req:"flask request",res:str) -> None:
    with open("walking.log","a") as log:
        print(req.form,req.host_url,req.remote_addr,res,file=log,sep="|")
    

@app.route('/')
def base():
    title = '步行路径规划'
    return render_template('entry.html',the_title=title,)

@app.route('/search0',methods = ['POST'])
def do_search_0() -> 'html':
    key = request.form['key']
    start_address = request.form['start_address']
    end_address = request.form['end_address']
    title = '查询结果如下：'
    df = direction_of_walking.direction_walking(key,start_address,end_address)
    results1 = df.loc[:,['instruction']]
    results2 = df.loc[:,['distance']]
    results3 = df.loc[:,['duration']]
    results1.columns = ['指引']
    results2.columns = ['路程']
    results3.columns = ['时间']
    total_walk = direction_of_walking.total_walk(df)
    total_walk_time = direction_of_walking.total_walk_time(df)
    route = results1['指引'].tolist()
    log_request(request,route)
    return render_template('results.html',the_title=title,the_start_address=start_address,the_end_address=end_address,the_results1=results1,the_results2=results2,the_results3=results3,the_html_table=results1.to_html(index=False),the_total_walk=total_walk,the_total_walk_time=total_walk_time)

@app.route('/viewlog')
def view_the_log() -> 'html':
    contents = []
    with open("walking.log","r") as log:
        for line in log:
            contents.append([])
            for item in line.split("|"):
                contents[-1].append(escape(item))
    title = ["Formdata","Host_url","remote_addr","results"]
    return render_template('log.html',the_title='查看日志',the_row_titles=title,the_data=contents)

if __name__ == '__main__':
    app.run(debug=True)